// page/component/new-pages/cart/cart.js
import Dialog from '../../../youzan/youzan_dist/dialog/dialog';
var request_api = require('../../../utils/require_api.js');
import Toast from '../../../youzan/youzan_dist/toast/toast';
const app = getApp()
Page({
  data: {
    carts: [], // 购物车列表
    hasList: false, // 列表是否有数据
    totalPrice: 0, // 总价，初始为0
    selectAllStatus: false, // 全选状态，默认全选
    order_item: [],
  },
  onShow() {
    console.log(app.globalData,"我又没有数据")
    var that = this;
    request_api.request(
      'shoppongcartAllData', //需要传给wxrequest.js 的 url
      {
        uid: app.globalData.openid
      }, //需要传的 data
      function(res) {
        if (res.data.length == 0) {
          that.setData({
            hasList: false,
          });
        } else {
          that.setData({
            hasList: true,
            carts: res.data
          });
        }
        that.getTotalPrice();
      },
      function() {
        console.log("錯誤");
      },
    )
  },

  //点击跳转页面到提交订单页面
  go_to_orders() {
    var flag = false;
    var isselect = false;
    var toorderparamer = [];
    for (let i = 0; i < this.data.carts.length; i++) {
      if (this.data.carts[i].selected) {
        flag = true;
        toorderparamer.push(this.data.carts[i]);
      } else {

      }
    }
    var select = '';
    for (let i = 0; i < toorderparamer.length; i++) {
      if (i == toorderparamer.length - 1) {
        select = select + toorderparamer[i].id;
      } else {
        select = select + toorderparamer[i].id + ',';
      }
    }
    if (!flag) {
      Toast('请至少选择一项商品！！！');
    } else {
      //准备提交订单时候先去判断是否还有库存
      request_api.request(
        'getorders_item', {
          id: select
        },
        function(res) {
          var goods_id = [];
          var colorId = [];
          var Filed = [];
          var num = [];
          for (let i = 0; i < res.data.length; i++) {
            goods_id.push(res.data[i].goods_id);
            colorId.push(res.data[i].colorId);
            Filed.push(res.data[i].Filed);
            num.push(res.data[i].num);
          }
          var isofno = [];
          var flag = false;
          for (let i = 0; i < goods_id.length; i++) {
            request_api.request(
              'getstockisno', //需要传给wxrequest.js 的 url
              {
                style_id: goods_id[i],
                ColorID: colorId[i],
                Filed: Filed[i],
                Quantity: num[i]
              }, //需要传的 data
              function(res) {
                console.log(res.data[0].isno);
                isofno.push(res.data[0].isno)
              },
              function() {
                console.log("錯誤");
              },
            )

          }
          setTimeout(function() {
            var index = '';
            for (let i = 0; i < isofno.length; i++) {
              if (isofno[i] == 0) {
                flag = true;
                index = index+ '   ' + (i + 1)
              }
            }

            if (flag) {
              Toast('您所选择的第' + index + '项超过了现有库存数量，请重新选择！！');
            } else {
              Toast.loading({
                duration: 2000, // 持续展示 toast
                forbidClick: true, // 禁用背景点击
                message: '加载中......',
                loadingType: 'spinner',
              });
              wx.navigateTo({
                url: '../orders/orders?order_item=' + select,
              })
            }


          }, 1000);
        },
        function() {
          console.log("錯誤");
        },
      )


    }
  },
  /**
   * 当前商品选中事件
   */
  selectList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    const selected = carts[index].selected;
    carts[index].selected = !selected;
    this.data.order_item = [];
    for (let i = 0; i < carts.length; i++) {
      if (carts[i].selected) {
        this.data.order_item.push(carts[i].id);
      }
    }
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },
  /**
   * 删除购物车当前商品
   */
  deleteList(e) {
    var that = this;
    Dialog.confirm({
      title: '确认信息',
      message: '确认删除该商品信息吗？'
    }).then(() => {
      const index = e.currentTarget.dataset.index;
      const item = e.currentTarget.dataset.item;
      request_api.request(
        'delete_shopping_cart', //需要传给wxrequest.js 的 url
        {
          id: item.id
        }, //需要传的 data
        function(res) {
          let carts = that.data.carts;
          carts.splice(index, 1);
          that.setData({
            carts: carts
          });
          if (!carts.length) {
            that.setData({
              hasList: false
            });
          } else {
            that.getTotalPrice();
          }
        },
        function() {
          console.log("錯誤");
        },
      )
    }).catch(() => {
      console.log("我是取消");
    });
  },
  //没有购商品跳转到首页去挑选商品
  goIndex() {
    wx.switchTab({
      url: '../../index/index',
    })
  },
  /**
   * 购物车全选事件
   */
  selectAll(e) {
    console.log(e);
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;
    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts
    });
    this.getTotalPrice();
  },

  /**
   * 绑定加数量事件
   */
  addCount(e) {

    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].num;
    num = num + 1;
    if (num > 50) {
      Toast('同一单品最多只能购买50件！！！');
      return false;
    }
    carts[index].num = num;
    console.log(carts[index], "carts[index]");
    this.set_num(carts[index].num, carts[index].id);
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },
  set_num(a, b) {
    var that = this;
    request_api.request(
      'update_shoppingcartNum', //需要传给wxrequest.js 的 url
      {
        "num": a,
        "id": b
      }, //需要传的 data
      function(res) {
        console.log(res);
      },
      function() {
        console.log("錯誤");
      },
    )
  },
  /**
   * 绑定减数量事件
   */
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    const obj = e.currentTarget.dataset.obj;
    let carts = this.data.carts;
    let num = carts[index].num;
    if (num <= 1) {
      return false;
    }

    num = num - 1;
    carts[index].num = num;
    this.set_num(carts[index].num, carts[index].id);
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },
  /**
   * 计算总价
   */
  getTotalPrice() {
    let carts = this.data.carts; // 获取购物车列表
    let total = 0;
    for (let i = 0; i < carts.length; i++) { // 循环列表得到每个数据
      if (carts[i].selected) { // 判断选中才会计算价格
        total += carts[i].num * carts[i].price; // 所有价格加起来
      }
    }
    this.setData({ // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  }
})